<template>
  <div class="box">
    <div class="container">
      <div class="search-box">
        <div class="search-top-box">
          <div class="search-top-right-box">
            <el-button type="primary" @click="addRole">添加角色</el-button>
          </div>
        </div>
      </div>
      <!-- table -->
      <div class="table-box">
        <el-table :header-cell-style="{ background: '#FAFBFC', color: '#828A9D', textAlign: 'center' }"
          :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" style="width: 100%"
          v-loading="loading">
          <el-table-column prop="name" label="角色名称" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="desc" label="角色描述" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="updated_at" label="更新时间" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="saveRole(scope.row)">修改</el-button>
              <el-button type="text" @click="delRole(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-pagination :page-sizes="[20, 50, 100]" class="el-pagination" @current-change="handleCurrentChange"
      :current-page="page" :page-size="num" @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 角色编辑弹窗 -->
    <el-dialog :title="editRoleType == 'add' ? '添加角色' : '修改角色'" :visible.sync="editRoleVisible" width="1200px">
      <div class="role-main">
        <el-form :model="roleInfoform" ref="saveRole" :rules="roleInfoRules" :inline="true" class="role-info">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleInfoform.name" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="desc">
            <el-input v-model="roleInfoform.desc" placeholder="请输入角色描述(非必填)"></el-input>
          </el-form-item>
        </el-form>
        <div class="perlabel">权限列表</div>
        <div v-if="!perList.length" style="margin-left: 10px">
          暂无权限，请前往 "<span class="jump" @click="jump">项目权限</span>"
          添加！
        </div>
        <div class="permission-list" v-else>
          <el-checkbox-group v-model="roleInfoform.checkedList">
            <div class="item-tr" v-for="(item, index) in perList" :key="index">
              <div class="item1-td">{{ item.name }}</div>
              <div class="item2-td">
                <div class="item2-tr" v-for="(item2, index2) in item.nodes" :key="index2">
                  <!-- 二级 -->
                  <template v-if="!item2.nodes.length">
                    <div class="item2-td-main">
                      <el-tooltip class="item" effect="dark" :content="item2.name" placement="right">
                        <div class="item2-td-name">
                          <el-checkbox :label="item2.id" @change="checkAll($event, index, index2)">{{ item2.name }}
                          </el-checkbox>
                        </div>
                      </el-tooltip>
                    </div>
                    <div class="item3-td item3-td-width">
                      <div class="item-fun" v-for="(item3, indx3) in item2.operation" :key="indx3">
                        <el-checkbox :label="item3.id">{{
                          item3.name
                        }}</el-checkbox>
                      </div>
                    </div>
                  </template>
                  <!-- 三级 -->
                  <template v-if="item2.nodes.length">
                    <div class="item2-td-main">
                      <el-tooltip class="item" effect="dark" :content="item2.name" placement="right">
                        <div class="item2-td-name">
                          <el-checkbox :label="item2.id" @change="checkAll($event, index, index2)">{{ item2.name }}
                          </el-checkbox>
                        </div>
                      </el-tooltip>
                    </div>
                    <div class="tree-box">
                      <div class="item2-tr" v-for="(item3, index3) in item2.nodes" :key="index3">
                        <div class="item2-td-main">
                          <el-tooltip class="item" effect="dark" :content="item3.name" placement="right">
                            <div class="item2-td-name">
                              <el-checkbox :label="item3.id" @change="checkAll($event, index, index2, index3)">{{
                                item3.name }}
                              </el-checkbox>
                            </div>
                          </el-tooltip>
                        </div>
                        <div class="item3-td">
                          <div class="item-fun" v-for="(item3, indx3) in item3.operation" :key="indx3">
                            <el-checkbox :label="item3.id">{{ item3.name }}</el-checkbox>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </el-checkbox-group>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sumbit" :loading="roleInfoform.submitBtn">提交</el-button>
        <el-button @click="editRoleVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import permissionApi from "@/api/permissionApi";

export default {
  name: '',
  data() {
    return {
      formSearch: {
        keyword: ''
      },

      loading: false,
      // 用户列表数据
      page: 1,
      num: 10,
      total: 0,
      tableData: [],

      // 权限列表数据
      perList: [],
      // 角色编辑弹窗
      editRoleVisible: false,
      editRoleType: "add",
      roleInfoform: {
        id: "",
        name: "",
        desc: "",
        checkedList: [],
        submitBtn: false,
      },
      roleInfoRules: {
        name: [{
          required: true,
          message: "请输入角色名称",
          trigger: "change"
        },],
      },
    }
  },
  watch: {

  },
  computed: {

  },
  mounted() {
    this.getPermissionList();
    this.getRoleList();
  },
  methods: {
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.page = 1;
      this.getRoleList();
    },
    // 搜索
    onSearch(page) {
      this.page = page || 1;
      this.getRoleList();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getRoleList();
    },


    // 获取权限列表
    getPermissionList() {
      permissionApi.getPermissionList().then((res) => {
        console.log(res, "getPermissionList");
        if (res.code == 200) {
          this.perList = res.data;
        }
      });
    },

    // 添加角色
    addRole() {
      this.editRoleType = "add";
      this.editRoleVisible = true;
      this.roleInfoform.checkedList = [];
      this.$nextTick(() => {
        this.$refs.saveRole.resetFields();
      });
    },
    // 编辑角色
    saveRole(row) {
      this.editRoleType = "edit";
      permissionApi
        .getRoleInfo({
          id: row.id,
        })
        .then((res) => {
          console.log(res, "getRoleInfo");
          if (res.code == 200) {
            this.roleInfoform.id = row.id;
            this.roleInfoform.name = res.data.name;
            this.roleInfoform.desc = res.data.desc ? res.data.desc : "";
            this.roleInfoform.checkedList = res.data.checkedList;
            this.editRoleVisible = true;
          } else {
            this.$message.error(res.message);
          }
        });
    },

    checkAll(state, idx, idx2, idx3) {
      console.log(state, idx, idx2, "state, idx, idx2", idx3)
      let perList = this.perList;
      let data = [];
      if (idx3 != undefined) {
        // 三级
        data = perList[idx].nodes[idx2].nodes[idx3].operation
      } else {
        // 二级
        if (perList[idx].nodes[idx2].nodes.length) {
          console.log(perList[idx].nodes[idx2].nodes);
          perList[idx].nodes[idx2].nodes.forEach((item) => {
            data.push(item);
            if (item.operation.length) {
              item.operation.forEach((child) => {
                data.push(child);
              });
            }
          });
        } else {
          data = perList[idx].nodes[idx2].operation;
        }
      }
      if (state) {
        this.setChecked(data);
      } else {
        this.setUnChecked(data);
      }
    },
    // 设置全不选
    setUnChecked(data) {
      let checkedList = this.roleInfoform.checkedList;
      data.forEach((item) => {
        if (checkedList.includes(item.id)) {
          var index = checkedList.indexOf(item.id);
          checkedList.splice(index, 1);
        }
      });
    },
    // 设置全选
    setChecked(data) {
      let checkedList = this.roleInfoform.checkedList;
      data.forEach((item) => {
        if (!checkedList.includes(item.id)) {
          checkedList.push(item.id);
        }
      });
    },

    jump() {
      this.editRoleVisible = false;
      this.$emit("change", "second");
    },
    // 修改perList数组变成一维
    setArrayFormat() {
      let perList = this.perList;
      let arr = [];
      perList.forEach((item) => {
        item.nodes.forEach((item2) => {
          var obj = {};
          obj.id = item2.id;
          obj.pid = item2.parent_id;
          arr.push(obj);
          if (item2.nodes.length) {
            item2.nodes.forEach((item3) => {
              var obj = {};
              obj.id = item3.id;
              obj.pid = item3.parent_id;
              arr.push(obj);
              item3.operation.forEach((item4) => {
                var obj = {};
                obj.id = item4.id;
                obj.pid = item4.parent_id;
                arr.push(obj);
              });
            });
          }
          item2.operation.forEach((item3) => {
            var obj = {};
            obj.id = item3.id;
            obj.pid = item3.parent_id;
            arr.push(obj);
          });
        });
      });
      return arr;
    },
    // 获取角色列表
    getRoleList() {
      this.loading = true;
      permissionApi
        .getRoleList({
          page: this.page,
          num: this.num,
        })
        .then((res) => {
          console.log(res, "getRoleList");
          this.loading = false;
          if (res.code == 200) {
            this.tableData = res.data.list;
            this.total = res.data.max;
          }
        })
        .catch((err) => {
          this.$message({
            message: err.message,
            type: "warning",
          });
        });
    },
    setRoleAdd(roleInfoform, checked_arr) {
      permissionApi
        .setRoleAdd({
          name: roleInfoform.name,
          desc: roleInfoform.desc,
          checked_arr: JSON.stringify(checked_arr),
        })
        .then((res) => {
          console.log(res, "setRoleAdd");
          if (res.code == 200) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.editRoleVisible = false;
            this.getRoleList();
          } else {
            this.$message.error(res.message);
          }
          this.roleInfoform.submitBtn = false;
        });
    },
    setRoleSave(roleInfoform, checked_arr) {
      permissionApi
        .setRoleSave({
          id: roleInfoform.id,
          name: roleInfoform.name,
          desc: roleInfoform.desc,
          checked_arr: JSON.stringify(checked_arr),
        })
        .then((res) => {
          console.log(res, "setRoleAdd");
          if (res.code == 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.editRoleVisible = false;
            this.getRoleList();
          } else {
            this.$message.error(res.message);
          }
          this.roleInfoform.submitBtn = false;
        });
    },
    sumbit() {
      this.$refs.saveRole.validate((valid) => {
        if (valid) {
          let roleInfoform = this.roleInfoform;
          // 选中的处理格式
          let checkedList = roleInfoform.checkedList;
          console.log(checkedList, "选中权限")
          if (checkedList.length < 1) {
            this.$message({
              message: "请选择至少一个权限",
              type: "warning",
            });
            return;
          }
          this.roleInfoform.submitBtn = true;
          let perList = this.setArrayFormat();
          let checked_arr = [];

          perList.forEach((item) => {
            if (checkedList.includes(item.id)) {
              checked_arr.push(item);
            }
          });
          if (this.editRoleType == "add") {
            this.setRoleAdd(roleInfoform, checked_arr);
          } else {
            this.setRoleSave(roleInfoform, checked_arr);
          }
        } else {
          return false;
        }
      });
    },
    delRole(row) {
      this.$confirm('是否删除 "' + row.name + '" 角色?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          permissionApi
            .setRoleDel({
              id: row.id,
            })
            .then((res) => {
              console.log(res, "setRoleDel");
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.getRoleList();
              } else {
                this.$message.error(res.message);
              }
            });
        })
        .catch(() => { });
    },
  }
}

</script>

<style lang="scss" scoped>
@import './index.scss';
</style>